package com.aiwiown.snackmq.broker.handler.console;

import com.aiwiown.snackmq.broker.auth.AuthorizationService;
import com.aiwiown.snackmq.cluster.metadata.MetadataManager;
import com.aiwiown.snackmq.cluster.raft.closeure.SnackMQApplyClosure;
import com.aiwiown.snackmq.common.auth.User;
import com.aiwiown.snackmq.common.handler.RequestContext;
import com.aiwiown.snackmq.common.message.Message;
import com.aiwiown.snackmq.common.message.MessageType;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Slf4j
public class CreateUserHandler extends AbstractLeaderRequiredConsoleHandler {

    public CreateUserHandler(MetadataManager metadataManager, AuthorizationService authorizationService) {
        super(metadataManager, authorizationService);
    }

    @Override
    public MessageType getMessageType() {
        return MessageType.CREATE_USER_REQUEST;
    }

    @Override
    protected void doHandle(RequestContext ctx, Message request) {
        // 权限和 Leader 检查已在基类中完成，这里只关注核心业务逻辑
        String username = request.getProperty("username");
        String password = request.getProperty("password");
        String rolesStr = request.getProperty("roles"); // e.g., "role1,role2"

        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
            SnackMQApplyClosure.sendErrorResponse(ctx, request, "Username and password cannot be empty.");
            return;
        }
        List<String> roles = (rolesStr == null || rolesStr.isEmpty())
                ? Collections.emptyList()
                : Arrays.asList(rolesStr.split(","));

        // 检查用户是否已存在
        if (metadataManager.getUser(username) != null) {
            SnackMQApplyClosure.sendErrorResponse(ctx, request, "User '" + username + "' already exists.");
            return;
        }

        // 创建 User 对象并提议到 Raft
        User newUser = new User(username, password, roles);
        SnackMQApplyClosure closure = new SnackMQApplyClosure(request, ctx, null);
        metadataManager.createUser(newUser, closure);
    }
}